{* $Id$ *}
{include_core file="admin/lib/header.html" title="合伙人代理下单"}
<script type="text/javascript" src="{$smarty.const.STATIC_URL}/js/jqueryui/1.8.11/minified/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="{$smarty.const.STATIC_URL}/js/jqueryui/1.8.11/minified/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="{$smarty.const.STATIC_URL}/js/jqueryui/1.8.11/minified/jquery.ui.position.min.js"></script>
<script type="text/javascript" src="{$smarty.const.STATIC_URL}/js/jqueryui/1.8.11/minified/jquery.ui.autocomplete.min.js"></script>
<style>
  #js_upFile{
    position: absolute;
    top:0px;
    z-index: 20001;
    opacity: 0;
  }
  .js_editDiscount input{
    width:40px;
  }

  .price_font{
    font-size: 16px !important;
  }
  .price_font em{
    color: red;
  }

</style>
{literal}
<script type="text/javascript">
$(function(){
  //搜索配置
    var cache = {},sInput=$("#sInput" ),lastXhr;
        sInput.data('initValue',sInput.val());
        sInput.focus(function(){if($(this).val()==sInput.data('initValue')) $(this).val('');}).blur(function(){if($(this).val()=='') $(this).val(sInput.data('initValue'));}).autocomplete({
            minLength: 2,
            source: function( request, response ) {
                var term = request.term;
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                lastXhr = $.getJSON('user/admin/get_store_mobile', request, function( data, status, xhr ) {
                    cache[ term ] = data;
                    if ( xhr === lastXhr ) {
                        response( data );
                    }
                });
            },
            select:function(event,ui){
                //选中做什么事情
                // alert(ui.item.link)
            }
        });
})

</script>
{/literal}
  <div class="page-header border-bottom clearfix">
    <h2 class="left">合伙人代理下单<span>在这里对合伙人进行下单</span></h2>
      {*<a href="{get_url()}&is_excel=1" class="btn btn-success btn-sm right">导出EXCEL</a>*}
  </div>
  <div class="search-form js_advancedForm">
    <form action="{AnUrl('order/admin/trade/trade_order')}" method="get" class="js_orderSearchForm">
      <p>
        <label for="" class="search-f-label">登录帐号：</label>
        <input type="text" class="search-f-ipt1" id="sInput" name="search_filter[user_name]" value="{$search_filter.user_name}">
      </p>
      <p><label for="" class="search-f-label"></label><button type="submit" class="btn btn-success btn-xs js_searchBtn">搜索</button></p>
    </form>
  </div>
  <form action="{AnUrl('order/admin/trade/trade_cup_type')}" method="post" class="js_trade_form">
    <div class="search-form js_advancedForm">
      {if $store_info}
      <table class="list-table" style="width:200px">
        <thead>
          <tr>
            <th style="width:40px;">登录帐号</th>
            <th style="width:40px;">真实姓名</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{$user_info.user_name}</td>
            <td>{$user_info.realname}</td>
          </tr>
        </tbody>
      </table>
      <br />
      <input type="hidden" name="store_id" value="{$store_info.id}" class="js_store_id">
      <p style="display:none;">
        <label for="" class="search-f-label">配送类型：</label>
        {$deliver_type = order_config::$deliver_type}
        <select class="search-f-slt1" name="deliver_type">
        {foreach $deliver_type as $k => $v}
          <option value="{$k}">{$v}</option>
        {/foreach}
        </select>
      </p>
      <p style="display:none;">
        <label for="" class="search-f-label">支付类型：</label>
        {$pay_type = order_config::$pay_type}
        <select class="search-f-slt1" name="pay_type">
        {foreach $pay_type as $k => $v}
          <option value="{$k}">{$v}</option>
        {/foreach}
        </select>
      </p>
      <p style="height:auto;display:none;">
        <label for="" class="search-f-label">备注：</label>
        <textarea name="note" class="add-f-area" style="resize: none;"></textarea>
      </p>
      {else}
      <p>没有相关合伙人信息</p>
      {/if}
    </div>
    <!--start:列表-->
    <table class="list-table">
      <thead><tr>
        {if $status == 1}
        <th style="width:20px;"><input type="checkbox" class="selectAll"></th>
        {/if}
        <th style="width:10px;">ID</th>
        <th style="width:60px;">封面</th>
        <th style="min-width:150px;">商品信息</th>
        <th style="width:60px;">SKU信息</th>
        <th style="width:60px;">单价</th>
        <th style="width:60px;">数量</th>
      </tr></thead>
      <tbody class="js_goods_list">
        {foreach $goods_list as $k=>$v}
        {if $v.cover}
        {$cover = _uri('attachment', (int)$v.cover, 'path')}
        {$image = _image($cover, small)}
        {/if}
        {$count_sku_num = count($v.sku_list)}
          <tr id="dataList{$v.id}" data-id="{$v.id}" data-price="{$v.price}" data-cover="{$image}" data-title="{$v.title}" {if $k%2 == 1} class="bg-gray"{/if} data-id="{$v.id}" data-relation_ids="{goods_helper::get_goods_relation_ids($v.id)}">
          {foreach $v.sku_list as $sk => $sv}
            {if $status == 1}
            <td rowspan="{$count_sku_num}"><input type="checkbox" class="listSelect"></td>
            {/if}
            <td rowspan="{$count_sku_num}">
              {$v.id}
            </td>
            <td rowspan="{$count_sku_num}">
              <img width="70" src="{$image}">
            </td>
            <td rowspan="{$count_sku_num}">
              商品分类：{_uri('category', $v.category_id, 'title')}<br />
              商品标题：{$v.title}<br />
              商品简介：{$v.intro}
            </td>
            <td>默认</td>
            <td>{$sv.price}</td>
            <input type="hidden" name="goods_list[goods_id][]" value="{$v.id}">
            <input type="hidden" name="goods_list[sku_id][]" value="{$sv.id}">
            <td class="js_editDiscount"><input type="text" value="0" name="goods_list[goods_num][]" data-price="{$sv.price}" class="js_goods_num"/></td>
          {/foreach}
          </tr>
        {foreachelse}
            <tr><td class="txtleft" colspan="11">暂无数据</td></tr>
        {/foreach}
        <tr><td class="txtright price_font" colspan="11">订单总金额：￥<em class="js_price_num">0</em>元</td></tr>
      </tbody>
      <tfoot>
        <tr><td colspan="11"><button type="submit" class="btn btn-success btn-xs js_trade_order">提交订单</button></td></tr>
      </tfoot>
    </table>
  </form>
<!--end:列表-->
{load_js file='zclip/jquery.zclip.min.js'}
{load_js file='zclip/ZeroClipboard.js'}
{load_js file='uploadify/jquery.uploadify.min.js'}
<script>
var resName = 'goods';
var jsCategoryId = "{$search_filter.category_id}";
$('.js_categoryId').load(siteUrl+'/category/load_category_option?res_name='+resName,function(){
  $('.js_categoryId').find('option').each(function(){
    if ($(this).attr('value') == jsCategoryId) {
      $(this).attr('selected','selected');
    }
  });
});
$(function(){
  $('.js_trade_order').click(function(e){
    e.preventDefault();
    var is_trade = 0;
    $('.js_goods_num').each(function(){
      var tmp_num = parseInt($(this).val());
      if(tmp_num && tmp_num > 0) {
        is_trade = 1;
      }
    });
    if(is_trade) {
      $('.js_trade_form').submit();
    } else {
      showMsg('您至少设置一个购买商品的数量');
      return;
    }

    showMsg('正在提交中....', 1, 1);
  })
  $('.js_goods_num').keyup(function(){
    autoNum($(this));
  })
  $('.js_goods_num').blur(function(){
    var order_price_sum = 0;
    $('.js_goods_num').each(function(){
      var goods_num = $(this).val();
      var goods_price = $(this).data('price');
      order_price_sum = order_price_sum+goods_num*goods_price;
      $('.js_price_num').html(order_price_sum);
    })
  });
  // 高级搜索
  $('.js_advanced').click(function(e){
    e.preventDefault();
    var thisObj = $(this);
    var outBox  = thisObj.closest('form');
    if (thisObj.hasClass('js_isOpen')) {
      thisObj.removeClass('js_isOpen open');
      outBox.find('input').show();
      outBox.find('button').show();
      $('.js_advancedForm').hide();
    } else {
      thisObj.addClass('js_isOpen open');
      outBox.find('input').hide();
      outBox.find('button').hide();
      $('.js_advancedForm').show();
    }
  });

  // 高级搜索时间验证
  $('.js_searchBtn').click(function(e){
    e.preventDefault();
    var thisObj   = $(this);
    var startDate = $.trim($('#startDate').val());
    var stopDate  = $.trim($('#stopDate').val());
    if (startDate > stopDate) {
      showMsg('结束时间应大于等于开始时间');
      return;
    }
    thisObj.closest('form').submit();
  });

  // 页面复制
  var clip = new ZeroClipboard( $('.js_copyList'), {
    moviePath: "../../../../js/zclip/ZeroClipboard.swf"
  });
  clip.on( 'complete', function(client, args) {
    showMsg("复制成功，复制内容为："+ args.text, 1);
  });


  $('.js_discountDiv').on('click', '#js_cancel', function(){
    closeDiv();
  });

  $('.js_discountDiv').next().click(function(){
    closeDiv();
  });

  $('.js_sltGoods').click(function(){
    $('.js_realtionGoods').html('努力加载中...');
    var goods     = $(this).closest('tr')
    var goodsId   = goods.data('id');
    if (!goodsId) {
      showMsg('请选择需要操作的商品');
      return;
    }
    var title     = goods.data('title');
    var price     = goods.data('price');
    var cover     = goods.data('cover');
    var height    = $(window).height();
    var width     = $(window).width();
    var divHeight = $('.js_discountDiv').height();
    var divWidth  = $('.js_discountDiv').outerWidth();
    var top       = $(document).scrollTop()+(height - divHeight)/3;
    var left      = (width - divWidth)/2 - 200;
    top = top < 0 ? 0: top;
    left = left < 0 ? 0: left;
    $('.js_mainGoods').children().eq(0).html('<img src="'+cover+'" width="40">').next().html('商品标题：'+title+'<br>商品价格:'+price);
    $('.js_discountDiv').css({ position:'absolute', display:'block', top:top+"px", left:left+"px" });
    $('.js_discountDiv').next().css('display', 'block');
    $('#js_addRalation').attr('data-goods_id', goodsId);
    getRelationList(goodsId);
  });

  $('js_discountDiv').on('click', '.js_deleteRelation', function(e){
    e.preventDefault();
    var href   = $(this).data('href');
    var currTr = $(this).closest('tr');
    var currTbody = $(this).closest('tbody');
    showConfirm('确定要删除当前关联商品？', 1, function(){
      $.post(href, {  }, function(json){
        if (json.info == 'ok') {
          currTr.remove();
          if (currTbody.children('tr').length == 0) {
            $('.js_realtionGoods').html('当前商品还有没关联商品');
          }
        } else {
          showMsg(json.info);
        }
      }, 'json');
    });
  });

  $('.js_discountDiv').on('click', '.js_editRelation', function(){
    var currType     = $(this).data('type');
    var parentTr = $(this).closest('tr');
    if (currType == 'edit') {
      var discount = parseInt(parentTr.find('.js_editDiscount').html());
      parentTr.find('.js_editDiscount').html('<input type="text" value="'+discount+'">');
      $(this).html('保存').next().hide();
      $(this).data('type', 'save');
    } else {
      var discount  = parentTr.find('.js_editDiscount').children('input').val();
      var salePrice = parentTr.find('.js_editDiscount').data('sale_price');
      var id        = $(this).data('id');
      var url       = "{AnUrl('goods/admin/eidt_realtion_goods')}";
      $.post(url, { id:id, discount:discount, sale_price:salePrice }, function(json){
        if (json.info == 'ok') {
          showMsg('修改成功');
        } else {
          showMsg(json.info);
        }
      }, 'json');
      parentTr.find('.js_editDiscount').html(discount);
      $(this).html('编辑').next().show();
      $(this).data('type', 'edit');
    }

  });
  $('.js_discountDiv').on('keyup', '.js_editDiscount input', function(){
    var parentTr = $(this).closest('tr');
    var discount = $(this).val();
    var price    = parseFloat($(this).parent().data('price'));
    var salePrice = discountMath(price, discount);
    $(this).parent().data('sale_price', salePrice);
    parentTr.find('.js_salePrice').html(salePrice);
  });

  $('.js_discountDiv').on('click', '#js_addRalation', function(){
    var goodsId = $(this).data('goods_id');
    addRelationGoods(goodsId);
  });

  // 显示信息
  $('.js_showInfo').on('mouseenter keydown', function(e){
    var cover = $(this).data('cover');
    var title = $(this).data('title');
    var price = $(this).data('price');
    var discount = $(this).data('discount');
    var salePrice = $(this).data('sale_price');
    var goodsId = $(this).data('goods_id');

    $('.js_showInfoDiv').children('div').eq(0).html('<img src="'+cover+'" width="70">');
    $('.js_showInfoDiv').children('div').eq(1).html('商品ID：'+goodsId+'<br>商品标题：'+title+'<br>商品价格：￥'+price+''+'<br>商品折扣：'+discount+'折<br>优惠价格：￥'+salePrice);

    //获取鼠标的位置
    var baseW = $(this).width();
    var top  = $(this).offset().top;
    var left = $(this).offset().left;
    var divW = $('.js_showInfoDiv').width();
    var divH = $('.js_showInfoDiv').height();
    var divLeft = left - (divW-baseW)/2-210;
    var divTop  = top - 190;

    $('.js_showInfoDiv').css({ top:divTop+'px', left:divLeft+'px' }).show();
  });
  $('.js_showInfo').on('mouseleave', function(e){
    $('.js_showInfoDiv').hide();
  });
});
// 关闭弹窗
function closeDiv(){
  $('.js_discountDiv').next().css('display', 'none');
  $('.js_discountDiv').css('display', 'none');
  location.href = location.href;
}

var discountMath = function(price, num){
  var tmpNum = num;
  if (isNaN(tmpNum)) {
    tmpNum = 0;
  }
  if (tmpNum != 0) {
    tmpNum = Math.abs(tmpNum);
    var numLen = tmpNum.toString().length;
    var base   = '1';
    for (var i=0; i < numLen; i++) {
      base = base+'0';
    }
    var basic = parseInt(base);
    var discount = parseFloat(tmpNum / basic * parseFloat(price));
    return discount.toFixed(2);
  } else {
    return price.toFixed(2);
  }
}

// 获取选中的商品ids
function getGoodsIds()
{
  var goodsIds = new Array();
  $('#js_sltRelationGoods').find('.js_goodsIds').each(function(){
    if ($(this).attr('checked') == 'checked') {
      var id = $(this).closest('.select-goods').data('id');
      if (!isNaN(id) && typeof id != 'undefind') {
        goodsIds.push(id);
      }
    }
  });

  return goodsIds;
}

// 获取商品折扣
function getGoodsDiscount()
{
  var goodsIds = getGoodsIds();
  var idsLen = goodsIds.length;
  var discountArr = new Array();
  for (var i = 0; i < idsLen; i++) {
    var id = goodsIds[i];
    var discount = $('#js_sltRelationGoods').find('.goodsSale'+id).val();
    discountArr[i] = discount;
  }

  return discountArr;
}

// 获取商品价格
function getDiscountPrice()
{
  var goodsIds = getGoodsIds();
  var idsLen = goodsIds.length;
  var priceArr = new Array();
  for (var i = 0; i < idsLen; i++) {
    var id = goodsIds[i];
    var price = $('#js_sltRelationGoods').find('.goodsPrice'+id).html();
    priceArr[i] = price;
  }

  return priceArr;
}
// 自动转为数字
function autoNum(obj) {
  var currNum = obj.val();
  currNum = parseInt(currNum);
  if (isNaN(currNum)) {
    currNum = 0;
  };
  obj.val(currNum);
}
function autoFloat(obj) {
  var currNum = obj.val();
  currNum = parseFloat(currNum);
  if (isNaN(currNum)) {
    currNum = 0;
  };
  obj.val(currNum.toFixed(2));
}
</script>
{include_core file="admin/lib/footer.html"}
